package com.wyp168.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.wyp168.oss.service.OssService;
import com.wyp168.oss.uitls.ContextPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    //上传头像
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        String endpoint = ContextPropertiesUtils.END_POINT;
        String accessKeyId = ContextPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ContextPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ContextPropertiesUtils.BUCKET_NAME;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            System.out.println(endpoint);
            System.out.println(accessKeyId);
            System.out.println(accessKeySecret);
            System.out.println(bucketName);
            //获取文件上传输入流
            InputStream inputStream = file.getInputStream();

            //获取文件的实际名称
            String fileName = file.getOriginalFilename();

            //1.在文件名称里面添加唯一的值
            String uuid = UUID.randomUUID().toString().replace("-", "");
            fileName = uuid.concat(fileName);

            //2.把文件按照日期进行分类，方便后期管理
            //  2022/01/11/1.jpg
            //获取当前日期
            String nowDate = new DateTime().toString("yyyy/MM/dd");
            fileName = nowDate.concat("/").concat(fileName);


            //调用oss方法实现上传
            //第一个参数： BudketName
            //第一个参数： 上传到oss文件路径和文件名称
            ossClient.putObject(bucketName, fileName, inputStream);

            //返回上传之后的文件路径
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return null;
    }
}
